import Vue from 'vue'
import Router from 'vue-router'

// in development-env not use lazy-loading, because lazy-loading too many pages will cause webpack hot update too slow. so only in production use lazy-loading;
// detail: https://panjiachen.github.io/vue-element-admin-site/#/lazy-loading

Vue.use(Router)

/*重写路由的push方法*/
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return routerPush.call(this, location).catch(error=> error)
}

/* Layout */
import Layout from '../views/layout/Layout'

/**
 * hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu, whatever its child routes length
 *                                if not set alwaysShow, only more than one route under the children
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noredirect           if `redirect:noredirect` will no redirct in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar,
  }
 **/

export const constantRouterMap = [
    {
        path: '/login',
        component: () =>
            import('@/views/login/login'),
        hidden: true
    },
    {
        path: '/404',
        component: () =>
            import('@/views/404'),
        hidden: true
    },
    {
        path: '/',
        component: () => import('@/views/layout/Layout'),
        redirect: '/dashboard',
        name: 'Dashboard',
        hidden: true,
        children: [{
            path: 'dashboard',
            component: () =>
                import('@/views/dashboard/index')
        }]

    },
    {
        path: '/feedback/:from/:_id',
        component: getComponent('feedback'),
        hidden: true
    },
    {
        path: '/boon',
        component: getComponent('boon'),
        hidden: true
    },
    {
        path: '/w/:id',
        component: getComponent('w'),
        hidden: true
    },
    { path: '*', redirect: '/404', hidden: true }
]

//以sidebar一个rootnode为起点，创建一个路由树
function makeSidebarTreeNode(parent, authlist) {
    let new_root={
        path:"/" + parent.router_path,
        name:parent.router_name,
        meta:{title: parent.name},
        component:getComponent("root"),
        children:[]
    }

    var rootnode = {};//这个即为sidebar的一个顶级菜单项
    rootnode['path'] = "/" + parent.router_path;//顶级菜单项必须要加个根路径，否则404/
    rootnode['name'] = parent.router_name;
    rootnode['meta'] = { title: parent.name, icon: parent.router_meta_icon };
    rootnode['component'] = getComponent("root");//此处暂时写死使用顶级菜单项默认布局
    // 暂时不做重定向，如有需求，此处设置后需要同时修改SidebarItem.vue中的顶级路由跳转，目前顶级菜单项已禁止跳转
    // if (parent.router_redirect != "") {
    // rootnode['redirect'] = "/"+parent.router_path;
    // }
    if (parent.router_hidden == 1) {
        rootnode['hidden'] = true;
    }
    rootnode['children'] = [];
    var clen = 0;
    for (let i = 0; i < authlist.length; i++) {
        if (authlist[i].parent_id == parent.id) {
            //找到一个子节点，若子节点有孩子节点且这个子节点本身component有渲染界面，那么需要redirect
            //否则，直接添加至节点，并递归判断其孩子节点
            if (isHaveChildren(authlist[i], authlist)) {
                //添加当前节点
                if (authlist[i].router_layout == 1) {
                    //router_layout=1表示有渲染界面，component指向有rootview的layout，如果component不为空，那么需要redirect
                    rootnode['children'][clen] = {};
                    rootnode['children'][clen]['path'] = authlist[i].router_path + '/';//正常路由路径，此处不能为空字符串
                    rootnode['children'][clen]['name'] = authlist[i].router_name;//2018/11/20开发环境警告错误先注释掉
                    rootnode['children'][clen]['component'] = getComponent();//自定义的router-view容器，为了让自己可重定向跳转的同时也能让孩子节点的界面有渲染的容器
                    rootnode['children'][clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
                    if (authlist[i].router_meta_icon != "") {
                        rootnode['children'][clen]['meta']['icon'] = authlist[i].router_meta_icon;
                    }
                    if (authlist[i].router_hidden == 1) {
                        rootnode['children'][clen]['hidden'] = true;
                    }
                    if (authlist[i].router_component != "") {
                        rootnode['children'][clen]['redirect'] = authlist[i].router_path;
                        rootnode['children'][clen]['children'] = [{
                            path: '',//此处一定要是空字符串，即第一个子路由跳转为等于父路由
                            name: authlist[i].router_name,
                            hidden: true,//一定要hidden = true
                            component: getComponent(authlist[i].router_component),
                            meta: { title: authlist[i].name, is_keep: true, id: authlist[i].id }
                            // 不能有meta???为什么想不起来了 ，暂时先加上
                        }];
                        new_root.children.push({path:authlist[i].router_path,name:authlist[i].router_name,meta:{title: authlist[i].name, id: authlist[i].id},component:getComponent(authlist[i].router_component)});
                        //递归获取孩子的所有节点对象
                        // var cnodes = getChildrenNode(authlist[i], authlist);
                        var obj = getChildrenNode(authlist[i], authlist);
                        var cnodes=obj.childrens;
                        var new_cnodes=obj.new_childrens;
                        // console.log(new_cnodes,"new_cnodes111")
                        new_root.children.push(...new_cnodes);
                        for (let i = 0; i < cnodes.length; i++) {
                            rootnode['children'][clen]['children'][i + 1] = cnodes[i];
                        }
                    } else {
                        //递归获取孩子的所有节点对象
                        // var cnodes = getChildrenNode(authlist[i], authlist);
                        var obj = getChildrenNode(authlist[i], authlist);
                        var cnodes=obj.childrens;
                        var new_cnodes=obj.new_childrens;
                        // console.log(new_cnodes,"new_cnodes222")
                        new_root.children.push(...new_cnodes);
                        if (cnodes.length > 0) {
                            rootnode['children'][clen]['children'] = [];
                            for (let i = 0; i < cnodes.length; i++) {
                                rootnode['children'][clen]['children'][i] = cnodes[i];
                            }
                        }
                    }
                } else {
                    //直接添加当前节点
                    rootnode['children'][clen] = {};
                    rootnode['children'][clen]['path'] = authlist[i].router_path;
                    rootnode['children'][clen]['name'] = authlist[i].router_name;
                    if (authlist[i].router_component != "") {
                        rootnode['children'][clen]['component'] = getComponent(authlist[i].router_component);
                        new_root.children.push({path:authlist[i].router_path,name:authlist[i].router_name,meta:{title: authlist[i].name, id: authlist[i].id},component:getComponent(authlist[i].router_component)});
                    } else {
                        rootnode['children'][clen]['component'] = getComponent();
                    }
                    rootnode['children'][clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
                    if (authlist[i].router_meta_icon != "") {
                        rootnode['children'][clen]['meta']['icon'] = authlist[i].router_meta_icon;
                    }
                    //暂时不考虑重定向设置
                    // if (authlist[i].router_redirect != "") {
                    //     rootnode['children'][clen]['redirect'] = authlist[i].router_redirect;
                    // }
                    if (authlist[i].router_hidden == 1) {
                        rootnode['children'][clen]['hidden'] = true;
                    }
                    // rootnode['children'][clen]['children'] = getChildrenNode(authlist[i], authlist);
                    var obj = getChildrenNode(authlist[i], authlist);
                    rootnode['children'][clen]['children']=obj.childrens;
                    var new_cnodes=obj.new_childrens;
                    // console.log(new_cnodes,"new_cnodes333")
                    new_root.children.push(...new_cnodes);
                }
                //添加其他孩子节点
            } else {
                //无孩子节点，添加当前节点即可
                rootnode['children'][clen] = {};
                rootnode['children'][clen]['path'] = authlist[i].router_path;
                rootnode['children'][clen]['name'] = authlist[i].router_name;
                if (authlist[i].router_component != "") {
                    rootnode['children'][clen]['component'] = getComponent(authlist[i].router_component);
                    new_root.children.push({path:authlist[i].router_path,name:authlist[i].router_name,meta:{title: authlist[i].name, id: authlist[i].id},component:getComponent(authlist[i].router_component)});
                }
                rootnode['children'][clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
                if (authlist[i].router_meta_icon != "") {
                    rootnode['children'][clen]['meta']['icon'] = authlist[i].router_meta_icon;
                }
                //暂时不考虑重定向设置
                // if (authlist[i].router_redirect != "") {
                //     rootnode['children'][clen]['redirect'] = authlist[i].router_redirect;
                // }
                if (authlist[i].router_hidden == 1) {
                    rootnode['children'][clen]['hidden'] = true;
                }
            }
            //rootnode的孩子数加1
            clen++;
        }
    }
    // console.log(new_root,"new_root");
    return {rootnode,new_root};
}

//递归获取顶级菜单项的children node，获取子节点对象数组
function getChildrenNode(parent, authlist) {

    let new_childrens=[];

    var childrens = [];
    var clen = 0;
    for (let i = 0; i < authlist.length; i++) {
        if (authlist[i].parent_id == parent.id) {
            //找到一个子节点，若子节点有孩子节点且这个子节点本身component有渲染界面，那么需要redirect
            //否则，直接添加至节点，并递归判断其孩子节点
            childrens[clen] = {};
            childrens[clen]['path'] = authlist[i].router_path;
            childrens[clen]['name'] = authlist[i].router_name;
            if (authlist[i].router_component != "") {
                childrens[clen]['component'] = getComponent(authlist[i].router_component);
                // new_childrens.push({path:authlist[i].router_path,name:authlist[i].router_name,component:getComponent(authlist[i].router_component)})
            }
            childrens[clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
            if (authlist[i].router_meta_icon != "") {
                childrens[clen]['meta']['icon'] = authlist[i].router_meta_icon;
            }
            if (isHaveChildren(authlist[i], authlist)) {
                //添加当前节点
                // if (authlist[i].router_component != "" && authlist[i].router_hidden == 0 && parent.router_hidden == 0) {
                //无孩子节点，添加当前节点即可
                //暂时不考虑重定向设置
                // if (authlist[i].router_redirect != "") {
                //     childrens[clen]['redirect'] = authlist[i].router_redirect;
                // }
                if (authlist[i].router_hidden == 1) {
                    childrens[clen]['hidden'] = true;
                }
                if (authlist[i].router_layout == 1) {
                    //router_layout=1表示有渲染界面，component指向有rootview的layout，如果component不为空，那么需要redirect
                    childrens[clen] = {};
                    childrens[clen]['path'] = authlist[i].router_path + '/';//正常路由路径，此处不能为空字符串  +'/'是解决搜索出来根据name跳转页面BUG
                    childrens[clen]['name'] = authlist[i].router_name;//2018/11/20开发环境警告错误先注释掉
                    childrens[clen]['component'] = getComponent();//自定义的router-view容器，为了让自己可重定向跳转的同时也能让孩子节点的界面有渲染的容器
                    childrens[clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
                    if (authlist[i].router_meta_icon != "") {
                        childrens[clen]['meta']['icon'] = authlist[i].router_meta_icon;
                    }
                    if (authlist[i].router_hidden == 1) {
                        childrens[clen]['hidden'] = true;
                    }
                    if (authlist[i].router_component != "") {
                        childrens[clen]['redirect'] = authlist[i].router_path;
                        childrens[clen]['children'] = [{
                            path: '',//此处一定要是空字符串，即第一个子路由跳转为等于父路由
                            name: authlist[i].router_name,
                            hidden: true,//一定要hidden = true
                            component: getComponent(authlist[i].router_component),
                            meta: { title: authlist[i].name, is_keep: true, id: authlist[i].id }
                            // 不能有meta ????为什么想不起来了 ，暂时先加上
                        }];
                        new_childrens.push({path:authlist[i].router_path,name:authlist[i].router_name,meta:{title:authlist[i].name, id: authlist[i].id},component:getComponent(authlist[i].router_component)})
                        //递归获取孩子的所有节点对象
                        // var cnodes = getChildrenNode(authlist[i], authlist);
                        var obj = getChildrenNode(authlist[i], authlist);
                        var cnodes=obj.childrens;
                        var new_cnodes=obj.new_childrens;
                        new_childrens.push(...new_cnodes);
                        for (let i = 0; i < cnodes.length; i++) {
                            childrens[clen]['children'][i + 1] = cnodes[i];
                        }
                    } else {
                        //递归获取孩子的所有节点对象
                        // var cnodes = getChildrenNode(authlist[i], authlist);
                        var obj = getChildrenNode(authlist[i], authlist);
                        var cnodes=obj.childrens;
                        var new_cnodes=obj.new_childrens;
                        new_childrens.push(...new_cnodes);
                        if (cnodes.length > 0) {
                            childrens[clen]['children'] = [];
                            for (let i = 0; i < cnodes.length; i++) {
                                childrens[clen]['children'][i] = cnodes[i];
                            }
                        }
                    }
                } else {
                    //直接添加当前节点
                    childrens[clen] = {};
                    childrens[clen]['path'] = authlist[i].router_path;
                    childrens[clen]['name'] = authlist[i].router_name;
                    if (authlist[i].router_component != "") {
                        childrens[clen]['component'] = getComponent(authlist[i].router_component);
                        new_childrens.push({path:authlist[i].router_path,name:authlist[i].router_name,meta:{title:authlist[i].name, id: authlist[i].id},component:getComponent(authlist[i].router_component)})
                    } else {
                        childrens[clen]['component'] = getComponent();
                    }
                    childrens[clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
                    if (authlist[i].router_meta_icon != "") {
                        childrens[clen]['meta']['icon'] = authlist[i].router_meta_icon;
                    }
                    // if (authlist[i].router_redirect != "") {
                    //     childrens[clen]['redirect'] = authlist[i].router_redirect;
                    // }
                    if (authlist[i].router_hidden == 1) {
                        childrens[clen]['hidden'] = true;
                    }
                    //递归获取孩子的所有节点对象
                    // childrens[clen]['children'] = getChildrenNode(authlist[i], authlist);
                    var obj = getChildrenNode(authlist[i], authlist);
                    childrens[clen]['children']=obj.childrens;
                    var new_cnodes=obj.new_childrens;
                    new_childrens.push(...new_cnodes);
                }
                //添加其他孩子节点
            } else {
                //无孩子节点，添加当前节点即可
                childrens[clen] = {};
                childrens[clen]['path'] = authlist[i].router_path;
                childrens[clen]['name'] = authlist[i].router_name;
                if (authlist[i].router_component != "") {
                    childrens[clen]['component'] = getComponent(authlist[i].router_component);
                    new_childrens.push({path:authlist[i].router_path,name:authlist[i].router_name,meta:{title:authlist[i].name, id: authlist[i].id},component:getComponent(authlist[i].router_component)})
                }
                childrens[clen]['meta'] = { title: authlist[i].name, is_keep: true, id: authlist[i].id };
                if (authlist[i].router_meta_icon != "") {
                    childrens[clen]['meta']['icon'] = authlist[i].router_meta_icon;
                }
                //暂时不考虑重定向设置
                // if (authlist[i].router_redirect != "") {
                //     childrens[clen]['redirect'] = authlist[i].router_redirect;
                // }
                if (authlist[i].router_hidden == 1) {
                    childrens[clen]['hidden'] = true;
                }
            }
            //rootnode的孩子数加1
            clen++;
        }
    }
    return {childrens,new_childrens};
}

//判断authlist中是否有parent的孩子节点
function isHaveChildren(parent, authlist) {
    for (let i = 0; i < authlist.length; i++) {
        if (authlist[i].parent_id == parent.id) {
            return true;
        }
    }
    return false;
}

//从缓存中获取路由对象树，路由树权限数据在登录成功后获取并缓存下来
function getAuthRouter() {
    //添加无需登录即可获得的路由
    var routes = [{
        path: '/login',
        name: 'login',
        component: getComponent("login"),
        hidden: true
    },
        {
            path: '/feedback/:from/:_id',
            name: 'feedback',
            component: getComponent('feedback'),
            hidden: true
        },
        {
            path: '/boon',
            name: 'boon',
            component: getComponent('boon'),
            hidden: true
        },
        {
            path: '/w/:_id',
            name: 'w',
            component: getComponent('w'),
            hidden: true
        },
        {
            path: '/404',
            name: '404',
            component: getComponent("404"),
            hidden: true
        },
        {
            path: '/',
            component: getComponent("root"),
            redirect: '/dashboard',
            name: 'Dashboard',
            hidden: true,
            children: [{
                path: 'dashboard',
                name: 'index',
                component: getComponent('dashboard')
            }]
        },

        {
            path: '/blank',
            component: getComponent("root"),
            name: 'Blank',
            hidden: true,
            children: [{
                path: '/dashboard/blank',
                name: 'blank',
                component: getComponent('blank')
            }]
        },

    ];
    // 路由权限树数据存储在localStorage中，和登录成功后的token同等存储周期，退出登录后重新登录从服务器获取
    var authliststring = localStorage.getItem('AUTH_ROUTER');
    var authlist;
    if (authliststring) {
        authlist = JSON.parse(authliststring);
    } else {
        routes[7] = { path: '*', redirect: '/404', hidden: true };
        return routes;
    }
    //获取所有的顶级菜单项
    var parents = [];
    var j = 0;
    for (let i = 0; i < authlist.length; i++) {
        if (authlist[i].parent_id == 0) {
            parents[j] = authlist[i];
            j++;
        }
    }

    let sidebar_list=[];
    var k = 7
    for (let i = 0; i < parents.length; i++) {
        //每个顶级菜单项生成一个路由对象树
        let obj = makeSidebarTreeNode(parents[i], authlist);
        sidebar_list.push(obj.rootnode);
        routes[k] = obj.new_root;
        k++;
    }
    // console.log(sidebar_list,"side_list")
    localStorage.setItem('SIDEBAR', JSON.stringify(sidebar_list));

    ///////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////
    routes[k] = { path: '*', redirect: '/404', hidden: true };
    return routes;
}

function getComponent(comp_str) {
    if (!comp_str) {
        return () => import('@/views/layout/components/AppMain');
    }
    switch (comp_str) {
        case "404":
            return () => import("@/views/404");
        case "root":
            return () => import("@/views/layout/Layout");
        case "login":
            return () => import("@/views/login/login");
        case "feedback":
            return () => import("@/views/feedback");
        case "boon":
            return () => import("@/views/pages/boon");
        case "w":
            return () => import("@/views/pages/w");
        case "cg_index":
            return () => import("@/views/dashboard/cg_index");
        case "blank":
            return () => import("@/views/dashboard/blank");
        default:
            return () => import(`@/views/${comp_str}`);//此处是亮点!!，理由如下
    }
    // webpack 编译es6 动态引入 import() 时不能传入变量，例如import(dir) , 而要传入字符串 import('path/to/my/file.js')，
    // 这是因为webpack的现在的实现方式不能实现完全动态。但一定要用变量的时候，可以通过字符串模板来提供部分信息给webpack；
    // 例如import(`./path/${myFile}`), 这样编译时会编译所有./path下的模块，但运行时确定myFile的值才会加载，从而实现懒加载。
}
export default new Router({
    // mode: 'history', //后端支持可开
    // scrollBehavior: () => ({ y: 0 }),
    routes: getAuthRouter(),
    // 本地路由表constantRouterMap仅供本地调试配置使用
    // routes: constantRouterMap,
})